var operation = "A";
var indexRow = -1;

var arrClients = localStorage.getItem("clients");
arrClients = JSON.parse(arrClients);

if (arrClients === null) arrClients = [];

$(function(){
	List();
	
	$("#saveBtn").bind("click", function(){
		if(operation === "A")
			Add();
		else
			Edit();
	});


	$(".editBtn").bind("click", function(){
		operation = "E";
		
		indexRow = parseInt($(this).attr("name"));
		
		var client = arrClients[indexRow];

		$("#code").val(client.code);
		$("#name").val(client.name);
		$("#tel").val(client.tel);
		$("#email").val(client.email);
		
		$("#code").attr("readonly","readonly");
		$("#name").focus();
	});

	$(".excludeBtn").bind("click", function(){
		indexRow = parseInt($(this).attr("name"));
		
		Exclude();
		
		List();
	});
});

function View(){
	return localStorage.getItem("clients");
}

function Add(){
	var client = {
		code : $("#code").val(),
		name : $("#name").val(),
		tel : $("#tel").val(),
		email : $("#email").val()
	};
	arrClients.push(client);

	localStorage.setItem("clients", JSON.stringify(arrClients));
	alert("Added");
	
	List();
}

function Edit(){
	arrClients[indexRow] = {
		code : $("#code").val(),
		name : $("#name").val(),
		tel : $("#tel").val(),
		email : $("#email").val()
	};

	localStorage.setItem("clients", JSON.stringify(arrClients));
	alert("Edited");
	
	operation = "A";
	List();
}

function Exclude(){
	arrClients.splice(indexRow, 1);

	localStorage.setItem("clients", JSON.stringify(arrClients));
	alert("Excluded");
}

function List(){
	$("#list tbody").html("");

	for(var i in arrClients){
		var client = arrClients[i];
		
		$("#list tbody").append("<tr>");
		$("#list tbody").append("<td>" + client.code + "</td>");
		$("#list tbody").append("<td>" + client.name + "</td>");
		$("#list tbody").append("<td>" + client.tel + "</td>");
		$("#list tbody").append("<td>" + client.email + "</td>");
		$("#list tbody").append("<td><button type='button' class='btn btn-default btn-xs editBtn' name='" + i + "'><span class='glyphicon glyphicon-pencil'></span> Editar</button></td>");
		$("#list tbody").append("<td><button type='button' class='btn btn-default btn-xs excludeBtn' name='" + i + "'><span class='glyphicon glyphicon-remove'></span> Excluir</button></td>");
		$("#list tbody").append("</tr>");
	};
}